// pages/write/write.js
const app = getApp()
const modbusUtils = require('../../utils/modbus.js');
const { ModbusRTU, arrayBufferToArray, ByteUtil, int32ToBytes, ModbusError, ModbusErrorType } = require('../../utils/modbus')
const { getStringLength } = require('../../utils/stringUtils')

Page({
  data: {
    isConnected: false,
    scrollTop: 0, // 新增页面滚动位置
    // IO输出控制
    ioControls: {
      closeValve: false,
      openValve: false,
      angleGetZero: false,
      angleGetFull: false,
      angleGetZero2s: false,
      angleGetFull2s: false,
      saveParamAfterAngleGet: false,
      oneButtonOpeningCalibration:false,
    },
    // 控制值
    controlValues: {
      kd: '',
      temperature: '',
      equiNo: ''
    },
    // 通信参数
    modbusMode: '0',
    id_485: '',
    baudrate: '0',
    dataBits: '0',
    verifyBits: '0',
    stopBits: '0',
    controlMode: '0',
    // 日志
    logMessages: [],
    // 读取场景
    readType:'', //READ_ALL_SETTING  WRITE_SETTING
    // 弹窗相关
    showInputModal: false,
    inputModalValue: '',
    inputModalType: '',
    inputModalTitle: '',
    inputModalInputType: 'text',
    inputModalPlaceholder: '',
    modalInputFocused: false,
    keyboardHeight: 0
  },

  onLoad: function (options) {
    console.log('Write page loaded');
    this.checkConnectionStatus();

    this.readAllData();
    
    // 监听键盘高度变化
    wx.onKeyboardHeightChange((res) => {
      console.log('键盘高度变化:', res.height);
      if (this.data.showInputModal) {
        this.setData({
          keyboardHeight: res.height
        });
      }
    });
  },

  onShow: function () {
    console.log('Write page shown');
    
    // 检查设备连接状态
    if (!app.globalData.connectedDevice) {
      wx.switchTab({
        url: '/pages/index/index'
      });
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }
    
    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
    
    this.checkConnectionStatus();
    this.onBLECharacteristicValueChange();
    
    // 如果设备已连接，自动读取所有数据
    if (app.globalData.isConnected && app.globalData.connectedDevice) {
      console.log('设备已连接，自动读取所有数据');
      // 延迟一下再读取，确保页面完全加载
      setTimeout(() => {
        this.readAllData();
      }, 500);
    }
  },

  onUnload: function () {
    // 页面卸载时清理键盘监听
    wx.offKeyboardHeightChange();
  },

  // 检查连接状态
  checkConnectionStatus() {
    const app = getApp();
    const isConnected = app.globalData.isConnected && app.globalData.connectedDevice;
    this.setData({
      isConnected: isConnected
    });
    
    if (isConnected) {
      this.addLog('页面已连接设备: ' + app.globalData.connectedDevice);
    } else {
      this.addLog('页面未连接设备');
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },

  // 添加日志
  addLog(message) {
    const now = new Date();
    const timeStr = now.toLocaleTimeString();
    const logMessages = this.data.logMessages;
    logMessages.unshift({
      time: timeStr,
      message: message
    });
    
    // 限制日志数量
    if (logMessages.length > 50) {
      logMessages.pop();
    }
    
    this.setData({
      logMessages: logMessages
    });
    
    console.log(`[${timeStr}] ${message}`);
  },

  // 读取所有数据
  readAllData() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    this.addLog('开始读取所有数据');
    
    // 读取设备数据
    this.readDeviceData();
    
    // 读取配置参数
    // this.readConfigData();
  },

  // 读取设备数据
  readDeviceData() {
    const app = getApp();
    if (!app.globalData.characteristicId) {
      this.addLog('错误: 未找到写入特征值');
      return;
    }

    // 构建读取命令 - 读取保持寄存器 (功能码 03)
    const startAddress = 0; // 起始地址
    const registerCount = 100; // 读取16个寄存器
    
    const readCommand = ModbusRTU.readHoldingRegisters(
      1, 
      startAddress, 
      registerCount
    );
    this.data.readType = 'READ_ALL_SETTING'

    // 格式化十六进制显示
    const hexCommand = this.arrayBufferToHex(readCommand.buffer).toUpperCase();
    this.addLog(`发送读取命令: ${hexCommand}`);

    // 发送读取命令
    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: readCommand.buffer,
      success: (res) => {
        this.addLog('读取命令发送成功');
      },
      fail: (err) => {
        this.addLog(`读取命令发送失败: ${err.errMsg}`);
        wx.showToast({
          title: '读取失败',
          icon: 'none'
        });
      }
    });
  },

  // 读取配置数据
  readConfigData() {
    const app = getApp();
    if (!app.globalData.characteristicId) {
      return;
    }

    // 读取配置寄存器
    const configStartAddress = 0x0100; // 配置寄存器起始地址
    const configRegisterCount = 0x0008; // 读取8个配置寄存器
    
    const readConfigCommand = ModbusRTU.readHoldingRegisters(
      1, 
      configStartAddress, 
      configRegisterCount
    );

    // 格式化十六进制显示
    const hexCommand = this.arrayBufferToHex(readConfigCommand.buffer).toUpperCase();
    this.addLog(`发送配置读取命令: ${hexCommand}`);

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: readConfigCommand.buffer,
      success: (res) => {
        this.addLog('配置读取命令发送成功');
      },
      fail: (err) => {
        this.addLog(`配置读取命令发送失败: ${err.errMsg}`);
      }
    });
  },

  // IO控制开关事件处理
  onCloseValveChange(e) {
    this.setData({
      'ioControls.closeValve': e.detail.value
    });
    this.sendIOControl();
  },

  onOpenValveChange(e) {
    this.setData({
      'ioControls.openValve': e.detail.value
    });
    this.sendIOControl();
  },

  onAngleGetZeroChange(e) {
    this.setData({
      'ioControls.angleGetZero': e.detail.value
    });
    this.sendIOControl();
  },

  onAngleGetFullChange(e) {
    this.setData({
      'ioControls.angleGetFull': e.detail.value
    });
    this.sendIOControl();
  },

  onAngleGetZero2sChange(e) {
    this.setData({
      'ioControls.angleGetZero2s': e.detail.value
    });
    this.sendIOControl();
  },

  onAngleGetFull2sChange(e) {
    this.setData({
      'ioControls.angleGetFull2s': e.detail.value
    });
    this.sendIOControl();
  },

  onSaveParamAfterAngleGetChange(e) {
    this.setData({
      'ioControls.saveParamAfterAngleGet': e.detail.value
    });
    this.sendIOControl();
  },

  onOneButtonOpeningCalibrationChange(e) {
    this.setData({
      'ioControls.oneButtonOpeningCalibration': e.detail.value
    });
    this.sendIOControl();
  },

  // 工具方法：ArrayBuffer转十六进制字符串
  arrayBufferToHex(buffer) {
    const uint8Array = new Uint8Array(buffer);
    return Array.from(uint8Array)
      .map(byte => byte.toString(16).padStart(2, '0'))
      .join(' ');
  },

  // 发送IO控制命令（合成一个16位数，一次性写入）
  sendIOControl() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    this.setData({
      readType: 'WRITE_SETTING'
    });

    // 合成ioControl
    let ioControl = 0;
    if (this.data.ioControls.closeValve) ioControl |= (1 << 0);
    if (this.data.ioControls.openValve) ioControl |= (1 << 1);
    if (this.data.ioControls.angleGetZero) ioControl |= (1 << 4);
    if (this.data.ioControls.angleGetFull) ioControl |= (1 << 5);
    if (this.data.ioControls.angleGetZero2s) ioControl |= (1 << 6);
    if (this.data.ioControls.angleGetFull2s) ioControl |= (1 << 7);
    if (this.data.ioControls.saveParamAfterAngleGet) ioControl |= (1 << 8);
    if (this.data.ioControls.oneButtonOpeningCalibration) ioControl |= (1 << 11);

    const app = getApp();
    if (!app.globalData.characteristicId) {
      this.addLog('错误: 未找到写入特征值');
      return;
    }

    // 0x0200为IO输出控制寄存器
    // 使用writeHoldingRegisters方法，写入一个寄存器
    const writeCommand = ModbusRTU.writeHoldingRegisters(1, 0x0000, [ioControl]);

    // 格式化十六进制显示
    const hexCommand = this.arrayBufferToHex(writeCommand.buffer).toUpperCase();
    this.addLog(`发送IO控制命令: ioControl = ${ioControl}, 命令: ${hexCommand}`);

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: writeCommand.buffer,
      success: (res) => {
        this.addLog(`IO控制命令发送成功`);
        wx.showToast({
          title: 'IO控制已发送',
          icon: 'success'
        });
      },
      fail: (err) => {
        this.addLog(`IO控制命令发送失败: ${err.errMsg}`);
        wx.showToast({
          title: 'IO控制发送失败',
          icon: 'none'
        });
      }
    });
  },

  // 输入事件处理
  onKdInput(e) {
    this.setData({
      'controlValues.kd': e.detail.value
    });
  },

  onTemperatureInput(e) {
    this.setData({
      'controlValues.temperature': e.detail.value
    });
  },

  onEquiNoInput(e) {
    this.setData({
      'controlValues.equiNo': e.detail.value
    });
  },

  onDeviceIdInput(e) {
    this.setData({
      id_485: e.detail.value
    });
  },

  onInputFocus(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;

    wx.createSelectorQuery().select(`#${id}`).boundingClientRect(rect => {
      if (rect) {
        wx.pageScrollTo({
          scrollTop: rect.top + this.data.scrollTop, // 需要一个页面当前的scrollTop
          duration: 300
        });
      }
    }).exec();
  },

  onPageScroll(e) {
    // 保存页面的滚动位置
    this.setData({
      scrollTop: e.scrollTop
    })
  },

  // 发送控制值
  sendKdValue() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    const kdValue = parseFloat(this.data.controlValues.kd);
    if (isNaN(kdValue) || kdValue < 0 || kdValue > 100) {
      wx.showToast({
        title: '请输入0-100之间的数值',
        icon: 'none'
      });
      return;
    }

    this.sendControlValue('kd', 0x0001, kdValue); // 放大10倍存储
  },

  sendTemperatureValue() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    const tempValue = parseFloat(this.data.controlValues.temperature);
    if (isNaN(tempValue)) {
      wx.showToast({
        title: '请输入有效的温度值',
        icon: 'none'
      });
      return;
    }

    this.sendControlValue('temperature', 0x0002, tempValue * 100); // 放大100倍存储
  },

  sendEquiNoValue() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    //解析为long类型
    const equiNo = parseInt(this.data.controlValues.equiNo);
    
    if (isNaN(equiNo) || equiNo < 0) {
      wx.showToast({
        title: '请输入有效的序列号',
        icon: 'none'
      });
      return;
    }

    this.sendControlValueLong('equiNo', 0x005D, equiNo);
  },

  // 发送控制值通用方法
  sendControlValue(controlType, address, value) {
    const app = getApp();
    if (!app.globalData.characteristicId) {
      this.addLog('错误: 未找到写入特征值');
      return;
    }

    this.setData({
      readType: 'WRITE_SETTING'
    });

    const registerValue = Math.round(value);

    // 构建写入单个寄存器命令
    const writeCommand = ModbusRTU.writeHoldingRegisters(
      1,
      address,
      [registerValue]
    );

    // 格式化十六进制显示
    const hexCommand = this.arrayBufferToHex(writeCommand.buffer).toUpperCase();
    this.addLog(`发送${controlType}控制命令: 地址=${address}, 值=${value}, 命令: ${hexCommand}`);

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: writeCommand.buffer,
      success: (res) => {
        this.addLog(`${controlType} 控制命令发送成功`);
        wx.showToast({
          title: '控制命令已发送',
          icon: 'success'
        });
      },
      fail: (err) => {
        this.addLog(`${controlType} 控制命令发送失败: ${err.errMsg}`);
        wx.showToast({
          title: '控制命令发送失败',
          icon: 'none'
        });
      }
    });
  },

  sendControlValueLong(controlType, address, valueLong) {
    const app = getApp();
    if (!app.globalData.characteristicId) {
      this.addLog('错误: 未找到写入特征值');
      return;
    }

    //判断数据不能超过10位数字
    if (valueLong.toString().length > 10) {
      wx.showToast({
        title: '数据不能超过10位数字',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      readType: 'WRITE_SETTING'
    });


    // 1. 转为4字节大端
    const dataBytes = int32ToBytes(Number(valueLong));
    // 2. 拆分为两个16位无符号整数
    const writeInt32 = [
      (dataBytes[0] << 8) | dataBytes[1],
      (dataBytes[2] << 8) | dataBytes[3]
    ];
    // 3. 生成modbus命令
    const writeCommand = ModbusRTU.writeHoldingRegisters(1, address, writeInt32);
    const hexCommand = this.arrayBufferToHex(writeCommand.buffer).toUpperCase();
    this.addLog(`发送${controlType}控制命令: 地址=${address}, 值=${valueLong}, 命令: ${hexCommand}`);

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: writeCommand.buffer,
      success: (res) => {
        this.addLog(`${controlType} 控制命令发送成功`);
        wx.showToast({
          title: '控制命令已发送',
          icon: 'success'
        });
      },
      fail: (err) => {
        this.addLog(`${controlType} 控制命令发送失败: ${err.errMsg}`);
        wx.showToast({
          title: '控制命令发送失败',
          icon: 'none'
        });
      }
    });
  },

  // 单选按钮事件处理
  onModbusModeChange(e) {
    this.setData({
      modbusMode: e.detail.value
    });
  },

  onBaudrateChange(e) {
    this.setData({
      baudrate: e.detail.value
    });
  },

  onDataBitsChange(e) {
    this.setData({
      dataBits: e.detail.value
    });
  },

  onVerifyBitsChange(e) {
    this.setData({
      verifyBits: e.detail.value
    });
  },

  onStopBitsChange(e) {
    this.setData({
      stopBits: e.detail.value
    });
  },

  onControlModeChange(e) {
    this.setData({
      controlMode: e.detail.value
    });
  },

  // 写入设置
  writeSettings() {
    if (!this.data.isConnected) {
      wx.showToast({
        title: '请先连接设备',
        icon: 'none'
      });
      return;
    }

    this.addLog('开始写入设备设置');
    this.setData({
      readType: 'WRITE_SETTING'
    });

    const app = getApp();
    if (!app.globalData.characteristicId) {
      this.addLog('错误: 未找到写入特征值');
      return;
    }

    const settings = [
      { address: 0x0007, value: parseInt(this.data.modbusMode) },
      { address: 0x0008, value: parseInt(this.data.id_485) },
      { address: 0x0009, value: parseInt(this.data.baudrate) },
      { address: 0x000A, value: parseInt(this.data.dataBits) },
      { address: 0x000B, value: parseInt(this.data.verifyBits) },
      { address: 0x000C, value: parseInt(this.data.stopBits) },
      { address: 0x000E, value: parseInt(this.data.controlMode) }
    ];
    // 逐个写入设置
    this.writeSettingsSequentially(settings, 0);
  },

  // 顺序写入设置
  writeSettingsSequentially(settings, index) {
    if (index >= settings.length) {
      this.addLog('所有设置写入完成');
      wx.showToast({
        title: '设置写入完成',
        icon: 'success'
      });
      return;
    }

    const app = getApp();
    const setting = settings[index];
    
    const writeCommand = ModbusRTU.writeHoldingRegisters(
      1,
      setting.address,
      [setting.value]
    );

    // 格式化十六进制显示
    const hexCommand = this.arrayBufferToHex(writeCommand.buffer).toUpperCase();
    this.addLog(`写入设置 ${index + 1}/${settings.length}: 地址=${setting.address}, 值=${setting.value}, 命令: ${hexCommand}`);

    wx.writeBLECharacteristicValue({
      deviceId: app.globalData.connectedDevice.deviceId,
      serviceId: app.globalData.serviceId,
      characteristicId: app.globalData.characteristicId,
      value: writeCommand.buffer,
      success: (res) => {
        this.addLog(`设置 ${index + 1} 写入成功`);
        // 延迟后写入下一个设置
        setTimeout(() => {
          this.writeSettingsSequentially(settings, index + 1);
        }, 200);
      },
      fail: (err) => {
        this.addLog(`设置 ${index + 1} 写入失败: ${err.errMsg}`);
        wx.showToast({
          title: '设置写入失败',
          icon: 'none'
        });
      }
    });
    // setTimeout(() => {
    //   this.writeSettingsSequentially(settings, index + 1, deviceId);
    // }, 200);
  },

  onBLECharacteristicValueChange() {
    //先移除监听
    wx.offBLECharacteristicValueChange()
    
    wx.onBLECharacteristicValueChange((res) => {
      const value = res.value
      // 处理接收到的数据
      console.log('收到数据:', value)
      // 根据读取类型调用相应的解析方法
      if (this.data.readType === 'READ_ALL_SETTING') {
        this.parseReadAllDataResponse(value);
      } else if (this.data.readType === 'WRITE_SETTING') {
        //this.parseWriteConfigResponse(value);
      } else {
        // 默认解析设备数据
        // try {
        //   const resultParsed = parseDeviceDataResponse(value, 100)
        //   console.log('解析结果:', resultParsed)
          
        //   // 更新设备数据到界面
        //   this.setData({
        //     deviceData: {
        //       equiNo: resultParsed.equiNo || 0,
        //       softVersion: resultParsed.softVersion || 0,
        //       errorNo: resultParsed.errorNo || 0,
        //       kdValue: resultParsed.kdValue || 0,
        //       jsylValue: resultParsed.jsylValue || 0,
        //       hsylValue: resultParsed.hsylValue || 0,
        //       jswdValue: resultParsed.jswdValue || 0,
        //       hswdValue: resultParsed.hswdValue || 0,
        //       zdqs: resultParsed.zdqs || 0,
        //       dqjdcgq: resultParsed.dqjdcgq || 0
        //     }
        //   })
          
        //   // 添加日志
        //   this.addLog(`数据更新成功: 开度${resultParsed.kdValue}%, 进水压力${resultParsed.jsylValue}MPa`)
        // } catch (error) {
        //   console.error('数据解析失败:', error)
        //   this.addLog(`数据解析失败: ${error.message}`)
        // }
      }
    })
  },
  parseReadAllDataResponse(value) {
    try {
      // 移除前3个字节（设备地址、功能码、字节数）
      const dataBytesTmp = value.slice(3);
      const dataBytes = arrayBufferToArray(dataBytesTmp)
      // 解析各个字段
      const ioControl = this.bytesToInt16(dataBytes[0 * 2], dataBytes[0 * 2 + 1]);  // IO输出控制
      const fkdkz = this.bytesToUint16(dataBytes[1 * 2], dataBytes[1 * 2 + 1]);  // 阀开度控制
      const fwdkz = this.bytesToUint16(dataBytes[2 * 2], dataBytes[2 * 2 + 1]);  // 阀温度控制
      const reserve1 = this.bytesToInt16(dataBytes[3 * 2], dataBytes[3 * 2 + 1]); // 备用
      const reserve2 = this.bytesToInt16(dataBytes[4 * 2], dataBytes[4 * 2 + 1]); // 备用
      const reserve3 = this.bytesToInt16(dataBytes[5 * 2], dataBytes[5 * 2 + 1]); // 备用
      const reserve4 = this.bytesToInt16(dataBytes[6 * 2], dataBytes[6 * 2 + 1]); // 备用
      const modbusMode = this.bytesToInt16(dataBytes[7 * 2], dataBytes[7 * 2 + 1]); // Modbus模式
      const id_485 = this.bytesToInt16(dataBytes[8 * 2], dataBytes[8 * 2 + 1]); // 设备ID
      const baudrate = this.bytesToInt16(dataBytes[9 * 2], dataBytes[9 * 2 + 1]); // 波特率
      const dataBits = this.bytesToInt16(dataBytes[10 * 2], dataBytes[10 * 2 + 1]); // 数据位
      const verifyBits = this.bytesToInt16(dataBytes[11 * 2], dataBytes[11 * 2 + 1]); // 校验位
      const stopBits = this.bytesToInt16(dataBytes[12 * 2], dataBytes[12 * 2 + 1]); // 停止位
      const valluePWM = this.bytesToUint16(dataBytes[13 * 2], dataBytes[13 * 2 + 1]); // PWM值
      const controlMode = this.bytesToInt16(dataBytes[14 * 2], dataBytes[14 * 2 + 1]); // 控制模式
      const reserve5 = this.bytesToInt16(dataBytes[15 * 2], dataBytes[15 * 2 + 1]); // 保留
      const reserve6 = this.bytesToInt16(dataBytes[16 * 2], dataBytes[16 * 2 + 1]); // 保留
      const functionValidConfig = this.bytesToUint16(dataBytes[17 * 2], dataBytes[17 * 2 + 1]); // 功能有效配置
      const reserve7 = this.bytesToInt16(dataBytes[18 * 2], dataBytes[18 * 2 + 1]); // 保留
      const reserve8 = this.bytesToInt16(dataBytes[19 * 2], dataBytes[19 * 2 + 1]); // 保留
      // const equiNo = this.bytesToUint32(dataBytes[93 * 2], dataBytes[93 * 2 + 1], dataBytes[93 * 2 + 2], dataBytes[93 * 2 + 3]); // EquiNO
      const equiNo = ByteUtil.parseUint32FromArray(dataBytes, 93);
      // 解析IO控制位
      const isCloseValueValue = this.isBit1(ioControl, 0);
      const isOpenValueValue = this.isBit1(ioControl, 1);
      const angleGetZeroValue = this.isBit1(ioControl, 4);
      const angleGetfullValue = this.isBit1(ioControl, 5);
      const angleGetZero2sValue = this.isBit1(ioControl, 6);
      const angleGetfull2sValue = this.isBit1(ioControl, 7);
      const saveParamAfterAngleGetValueValue = this.isBit1(ioControl, 8);
      const oneButtonOpeningCalibration = this.isBit1(ioControl, 11);

      // 计算控制值
      const fkdkzValue = fkdkz;
      const fwdkzValue = fwdkz * 0.01;

      // 更新页面数据
      this.setData({
        // IO控制状态
        'ioControls.closeValve': isCloseValueValue,
        'ioControls.openValve': isOpenValueValue,
        'ioControls.angleGetZero': angleGetZeroValue,
        'ioControls.angleGetFull': angleGetfullValue,
        'ioControls.angleGetZero2s': angleGetZero2sValue,
        'ioControls.angleGetFull2s': angleGetfull2sValue,
        'ioControls.saveParamAfterAngleGet': saveParamAfterAngleGetValueValue,
        'ioControls.oneButtonOpeningCalibration': oneButtonOpeningCalibration,

        // 控制值
        'controlValues.kd': fkdkzValue.toString(),
        'controlValues.temperature': fwdkzValue.toFixed(2),
        'controlValues.equiNo': equiNo.toString(),

        // 通信参数
        modbusMode: modbusMode.toString(),
        id_485: id_485.toString(),
        baudrate: baudrate.toString(),
        dataBits: dataBits.toString(),
        verifyBits: verifyBits.toString(),
        stopBits: stopBits.toString(),
        controlMode: controlMode.toString()
      });

      this.addLog('全部数据读取成功！');
      wx.showToast({
        title: '全部数据读取成功！',
        icon: 'success'
      });

    } catch (error) {
      console.error('解析读取数据失败:', error);
      this.addLog(`解析读取数据失败: ${error.message}`);
      wx.showToast({
        title: '数据解析失败',
        icon: 'none'
      });
    }
  },

  // 工具方法：字节转16位有符号整数
  bytesToInt16(byte1, byte2) {
    const value = (byte1 << 8) | byte2;
    return (value & 0x8000) ? value - 0x10000 : value;
  },

  // bytesToInt16Debugger(byte1, byte2) {
  //   const value = (byte1 << 8) | byte2;
  //   return (value & 0x8000) ? value - 0x10000 : value;
  // },

  // 工具方法：字节转16位无符号整数
  bytesToUint16(byte1, byte2) {
    return (byte1 << 8) | byte2;
  },
  // bytesToUint16Debugger(byte1, byte2) {
  //   return (byte1 << 8) | byte2;
  // },
  // 工具方法：字节转32位无符号整数
  bytesToUint32(byte1, byte2, byte3, byte4) {
    return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
  },

  // 工具方法：检查指定位是否为1
  isBit1(value, bitPosition) {
    return (value & (1 << bitPosition)) !== 0;
  },

  parseWriteConfigResponse(value) {
    try {
      // 写入单个寄存器的响应通常是回显相同的命令
      // 检查响应是否成功（通常前3个字节是设备地址、功能码、寄存器地址）
      if (value.length >= 6) {
        const deviceAddress = value[0];
        const functionCode = value[1];
        const registerAddress = (value[2] << 8) | value[3];
        const registerValue = (value[4] << 8) | value[5];
        
        this.addLog(`写入配置响应: 设备${deviceAddress}, 功能码${functionCode}, 地址${registerAddress}, 值${registerValue}`);
        
        // 检查功能码是否为06（写入单个寄存器）
        if (functionCode === 0x06) {
          this.addLog('配置写入成功');
          wx.showToast({
            title: '配置写入成功',
            icon: 'success'
          });
        } else {
          this.addLog('配置写入失败: 功能码错误');
          wx.showToast({
            title: '配置写入失败',
            icon: 'none'
          });
        }
      } else {
        this.addLog('配置写入响应数据格式错误');
        wx.showToast({
          title: '响应数据格式错误',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('解析写入配置响应失败:', error);
      this.addLog(`解析写入配置响应失败: ${error.message}`);
      wx.showToast({
        title: '响应解析失败',
        icon: 'none'
      });
    }
  },

  // 弹窗相关方法
  onInputTap(e) {
    const type = e.currentTarget.dataset.type;
    let currentValue = '';
    let title = '';
    let inputType = 'text';
    let placeholder = '';
    // 根据类型设置对应的值、标题、输入类型和占位符
    console.log("abcd")
    switch (type) {
      case 'kd':
        currentValue = this.data.controlValues.kd || '';
        title = '阀开度控制';
        inputType = 'number';
        placeholder = '0-100';
        break;
      case 'temperature':
        currentValue = this.data.controlValues.temperature || '';
        title = '阀温度控制';
        inputType = 'number';
        placeholder = '温度值';
        break;
      case 'equiNo':
        currentValue = this.data.controlValues.equiNo || '';
        title = 'equi序列号';
        inputType = 'text';
        placeholder = '序列号';
        break;
      case 'id_485':
        currentValue = this.data.id_485 || '';
        title = '设备ID';
        inputType = 'number';
        placeholder = '设备ID';
        break;
      default:
        return;
    }

    console.log('弹窗初始值:', { type, currentValue, title, inputType, placeholder });

    // 先显示弹窗
    this.setData({
      showInputModal: true,
      inputModalType: type,
      inputModalTitle: title,
      inputModalInputType: inputType,
      inputModalPlaceholder: placeholder
    });

    // 使用 setTimeout 确保弹窗显示后再设置输入框的值
    setTimeout(() => {
      this.setData({
        inputModalValue: currentValue
      });
    }, 100);
  },

  onModalInputFocus(e) {
    console.log('弹窗输入框获得焦点');
    // 当输入框获得焦点时，确保弹窗内容可见
    this.setData({
      modalInputFocused: true
    });
  },

  onModalInputBlur(e) {
    console.log('弹窗输入框失去焦点');
    this.setData({
      modalInputFocused: false
    });
  },

  onModalInputChange(e) {
    const { inputModalType } = this.data;
    let value = e.detail.value;
    let maxDecimal = null;
    switch (inputModalType) {
      case 'kd':
        maxDecimal = 1;
        break;
      case 'temperature':
        maxDecimal = 2;
        break;
      // case 'pressure':
      //   maxDecimal = 3;
      //   break;
      default:
        maxDecimal = null;
    }
    if (maxDecimal !== null) {
      if (!this.checkDecimalPlaces(value, maxDecimal)) {
        // 超出小数位数，直接不更新
        return;
      }
    }
    this.setData({
      inputModalValue: value
    });
  },

  onModalConfirm() {
    const { inputModalType, inputModalValue } = this.data;
    
    console.log('确认弹窗输入:', { inputModalType, inputModalValue });
    let formattedValue = inputModalValue;
    let valid = true;
    let maxDecimal = 0;
    switch (inputModalType) {
      case 'kd':
        maxDecimal = 1;
        break;
      case 'temperature':
        maxDecimal = 2;
        break;
      // case 'pressure':
      //   maxDecimal = 3;
      //   break;
      default:
        maxDecimal = null;
    }
    if (maxDecimal !== null) {
      if (!this.checkDecimalPlaces(inputModalValue, maxDecimal)) {
        wx.showToast({
          title: `输入格式错误，最多${maxDecimal}位小数`,
          icon: 'none'
        });
        return;
      }
    }
    // 根据类型格式化输入
    switch (inputModalType) {
      case 'kd':
        formattedValue = this.formatDecimal(inputModalValue, 1);
        this.setData({
          'controlValues.kd': formattedValue
        });
        break;
      case 'temperature':
        formattedValue = this.formatDecimal(inputModalValue, 2);
        this.setData({
          'controlValues.temperature': formattedValue
        });
        break;
      case 'equiNo':
        this.setData({
          'controlValues.equiNo': inputModalValue
        });
        break;
      case 'id_485':
        this.setData({
          id_485: inputModalValue
        });
        break;
    }

    // 关闭弹窗
    this.setData({
      showInputModal: false,
      inputModalValue: '',
      inputModalType: '',
      inputModalTitle: '',
      inputModalInputType: 'text',
      inputModalPlaceholder: ''
    });
  },

  // 校验小数位数
  checkDecimalPlaces(val, maxDecimal) {
    if (typeof val !== 'string') val = String(val);
    if (val.indexOf('.') === -1) return true;
    const decimalPart = val.split('.')[1];
    return decimalPart.length <= maxDecimal;
  },

  // 格式化小数位工具
  formatDecimal(val, n) {
    let num = parseFloat(val);
    if (isNaN(num)) return '';
    return num.toFixed(n);
  },

  onModalCancel() {
    // 关闭弹窗，不保存数据
    this.setData({
      showInputModal: false,
      inputModalValue: '',
      inputModalType: '',
      inputModalTitle: '',
      inputModalInputType: 'text',
      inputModalPlaceholder: ''
    });
  },

  onModalOverlayTap() {
    // 点击遮罩层关闭弹窗
    this.onModalCancel();
  },

  onModalContentTap() {
    // 点击弹窗内容区域不关闭弹窗
    // 这里不需要做任何处理，只是阻止事件冒泡
  }
}); 